﻿using Seggu.Daos.Interfaces;
using Seggu.Data;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Transactions;
using System.Linq;

namespace Seggu.Daos
{
    public sealed class VehicleTypeDao: GenericDao<VehicleType>, IVehicleTypeDao
    {
        public void SaveVType(VehicleType newVehicleType)
        {
            var dbVehiceType = container.VehicleTypes
                                    //.Include("Uses")
                                    //.Include("Bodyworks")
                                    .Single(c => c.Id == newVehicleType.Id) ?? newVehicleType;
            newVehicleType.Id = dbVehiceType.Id;

            var bodyworks = new List<Bodywork>(newVehicleType.Bodyworks).ToList();
            dbVehiceType.Bodyworks.Clear();
            foreach (var dbBodyw in container.Bodyworks)
            {
                if (bodyworks.Any(bodw => bodw.Id == dbBodyw.Id))
                {
                    container.Bodyworks.Attach(dbBodyw);
                    dbVehiceType.Bodyworks.Add(dbBodyw);
                }
            }

            var uses = new List<Use>(newVehicleType.Uses).ToList();
            dbVehiceType.Uses.Clear();
            foreach (var dbUses in container.Uses)
            {
                if (uses.Any(use => use.Id == dbUses.Id))
                {
                    container.Uses.Attach(dbUses);
                    dbVehiceType.Uses.Add(dbUses);
                }
            }
            container.Entry(dbVehiceType).State = EntityState.Added;
            container.Entry(dbVehiceType).CurrentValues.SetValues(newVehicleType);
            container.SaveChanges();
        }
    }
}
